<template>
  <view class="as-us flex flex-1 flex-col items-center mt30">
    <u-form ref="formRef" :model="formData" :rules="rules" :label-width="200" style="width: 100%">
      <u-form-item label="反馈内容" prop="content" label-position="top">
        <u-input :type="textarea" textarea-height="200" textarea-maxlength="500" textarea-placeholder="请输入反馈内容"
                 textarea-auto-height="true" textarea-rows="5" v-model="formData.content" placeholder="请输入反馈内容"/>
      </u-form-item>
      <u-form-item label="图片上传" prop="image" label-position="top">
        <u-upload :action="action" :max-count="1" :before-upload="beforeUpload"
                  @on-uploaded="handleOnUploaded"></u-upload>
      </u-form-item>
    </u-form>
    <view class="footer-commit">
      <button @click="submit" class="commit_btn">立即提交</button>
    </view>
  </view>
</template>
<script setup lang="ts">
import {ref} from "vue"
import config from "@/config";
import {onReady} from "@dcloudio/uni-app";
import {apiFeedback} from "@/api/user";

const action = ref(config.baseUrl + 'api/upload/upImage')
const formData = ref({
  content: '',
  image: ''
});
const formRef = ref(null)
const rules = ref({
  content: [
    {
      required: true,
      message: '请输入反馈内容',
      trigger: 'blur'
    }
  ]
});

const beforeUpload = (index, list) => {
  console.log(list)
  // let images = ''
  // list.forEach(item => {
  //   if (item.response && item.response.data && item.response.data.url) {
  //     images = item['response'].data.url
  //   }
  // })
  // formData.value.image = images
}

const handleOnUploaded = (list) => {
  let images = ''
  list.forEach(item => {
    if (item.response && item.response.data && item.response.data.url) {
      images = item['response'].data.url
    }
  })
  formData.value.image = images
}

onReady(() => {
  formRef.value.setRules(rules)
})

const submit = async () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      const res = await apiFeedback(formData.value)
      uni.showToast({title: '提交成功', icon: 'success', mask: true});
      setTimeout(() => {
        uni.navigateBack();
        // 可选：重置表单验证状态
        if (typeof formRef.value?.resetFields === 'function') {
          formRef.value.resetFields();
        }
      }, 1500); // 延迟1.5秒跳转，确保Toast可见
    }
  })
}


</script>

<style lang="scss" scoped>
.as-us {
  height: 100vh;
  padding: 20rpx;
  background-color: white;

  .img {
    width: 160rpx;
    height: 160rpx;
    border-radius: 20rpx;
    margin-top: 96rpx;
  }
}


.footer-commit {
  position: fixed;
  bottom: 50rpx;
  left: 0;
  right: 0;
  padding: 20rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
}
</style>
